package com.clwl.supervise.superviseapp.controller.inspection;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.config.RepeatSubmit;
import com.clwl.supervise.superviseapp.entity.base.CommonSearchEntity;
import com.clwl.supervise.superviseapp.entity.base.DailySaveVo;
import com.clwl.supervise.superviseapp.entity.base.TcCompany;
import com.clwl.supervise.superviseapp.entity.pro.JgProCompanyDailyScore;
import com.clwl.supervise.superviseapp.entity.pro.JgTcCompany;
import com.clwl.supervise.superviseapp.entity.result.ResultEntity;
import com.clwl.supervise.superviseapp.entity.risk.JgPointDistance;
import com.clwl.supervise.superviseapp.entity.supervise.JgDailyCheck;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.service.company.TcCompanyService;
import com.clwl.supervise.superviseapp.service.inspect.DailyInspectService;
import com.clwl.supervise.superviseapp.service.inspect.DailyInspectV2Service;
import com.clwl.supervise.superviseapp.service.pro.JgProCompanyDailyScoreService;
import com.clwl.supervise.superviseapp.util.HolidayUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.YearMonth;
import java.util.*;

/**
 * 日常检查
 */
@RestController
@RequestMapping("dailyInspect/v2/")
public class DailyInspectV2Controller {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DailyInspectV2Service dailyInspectV2Service;
    @Autowired
    private DailyInspectService dailyInspectService;
    @Autowired
    private BaseDataService baseDataService;

    @Autowired
    private TcCompanyService tcCompanyService;

    @Autowired
    private JgProCompanyDailyScoreService jgProCompanyDailyScoreService;




    @GetMapping("getInspectionBaseInfo")
    @RepeatSubmit
    public ResultEntity<TcCompany> getInspectionBaseInfo(Long companyId) {
        try {
            if (companyId == null) {
                return ResultEntity.error("请传递企业id");
            }
            TcCompany company = dailyInspectV2Service.selectCheckInfo( companyId);
            List<Map<String, Object>> dictList = dailyInspectV2Service.getDictList();
            JgPointDistance distance = baseDataService.getCheckDistance(companyId + "");
            company.setDistance(distance.getDistance()+"");
            company.setAbnormalReasonTypeList(dictList);
            return ResultEntity.success(company);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 获取日常检查的检查项目列表
     *
     * @param checkId   检查iD
     * @param companyId 企业Id
     * @return
     */
    @GetMapping("checkItemList")
    public ResultEntity<Map<String, Object>> checkItemList(Long companyId) {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> itemList = dailyInspectV2Service.selectCheckItemList( companyId);
            result.put("templateName", itemList.size() > 0 ? itemList.get(0).get("TEMPLATE_NAME") : "");
            result.put("itemList", itemList);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 社会责任评分模版列表  社会责任评分标准表：jg_liability_standard，社会责任评分内容：jg_liability_content
     *
     * @param checkId
     * @param companyId
     * @return
     */
    @GetMapping("liabilityItemList")
    public ResultEntity<Map<String, Object>> liabilityItemList(Long checkId,Long dynamicScoringId, Long companyId) {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> mapList = dailyInspectService.selectLiabilityItem(checkId,dynamicScoringId, companyId);
            result.put("templateName", !mapList.isEmpty() ? mapList.get(0).get("TEMPLATE_NAME") : "");
            result.put("itemList", mapList);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 保存检查项结果内容
     *
     * @param checkId                 检查Id
     * @param templateId              模板id
     * @param standardId              检查标准id
     * @param contentId               检查内容Id
     * @param result                  选择的结果 1是、2否、3合理缺项
     * @param problemContent          问题描述选择的内容
     * @param checkExplain            检查说明选择的内容
     * @param problemContentInput     问题描述输入的内容
     * @param missingItemContentInput 检查说明输入的内容
     * @param taskIds                 关联合并任务的id
     * @return
     * @deprecated 页面不实时保存
     */
    @PostMapping("saveCheckItem")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveCheckItem(Long checkId, Long templateId, Long standardId, Long contentId, String result,
                                      String problemContent, String checkExplain, String problemContentInput, String missingItemContentInput, String taskIds
    ) {
        try {
            dailyInspectService.saveCheckItem(checkId, standardId, contentId, result,
                    problemContent, checkExplain, problemContentInput, missingItemContentInput);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置当前的检查内容失败checkId:{},checkNum:{},templateId:{},standardId:{}, contentId:{}, result:{},   problemContent:{}, checkExplain:{}",
                    checkId, templateId, standardId, contentId, result, problemContent, checkExplain);
            return ResultEntity.error("上传失败");
        }
    }


    @PostMapping("saveLiability")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveLiability(Long checkId, Long templateId, Long standardId, Long contentId, String result,
                                      String problemContent, String checkExplain, String problemContentInput, String missingItemContentInput, String taskIds
    ) {
        try {
            dailyInspectService.saveLiability(checkId, standardId, contentId, result,
                    problemContent, checkExplain, problemContentInput, missingItemContentInput);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置当前的检查内容失败checkId:{},checkNum:{},templateId:{},standardId:{}, contentId:{}, result:{},   problemContent:{}, checkExplain:{}",
                    checkId, templateId, standardId, contentId, result, problemContent, checkExplain);
            return ResultEntity.error("上传失败");
        }
    }


    /**
     * 保存检查门头照照片
     *
     * @param checkId 检查Id
     * @param file    门头照文件
     * @return
     */
    @PostMapping("uploadCheckFile")
    public ResultEntity uploadCheckFile(Long checkId, MultipartFile file) {
        try {
            JgDailyCheck check = dailyInspectService.uploadCheckFile(checkId, file);
            return ResultEntity.success(check);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 上传检查项的问题照片
     *
     * @param checkId    检查id
     * @param standardId 检查标准id
     * @param contentId  检查内容Id
     * @param file
     * @return
     * @deprecated 页面不实时上传了
     */
    @PostMapping("uploadItemFile")
    public ResultEntity uploadItemFile(Long checkId, Long standardId, Long contentId, MultipartFile file
    ) {
        try {
            String fileUrl = dailyInspectService.uploadItemFile(checkId, standardId, contentId, file);
            return ResultEntity.success(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置当前的检查内容失败checkId:{},standardId:{}, contentId:{}",
                    checkId, standardId, contentId);
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 保存/临时保存检查项结果内容
     *
     * @return
     */
    @PostMapping("saveCheckInfo")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveCheckInfo(DailySaveVo dailySaveVo) {
        try {
            JgDailyCheck dailyCheck = dailyInspectService.saveCheckInfo(dailySaveVo, false);
            return ResultEntity.success(dailyCheck);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存/临时保存检查项结果内容失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 最终保存
     * @return
     */
    @PostMapping("finaSaveInfo")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity finaSaveInfo(DailySaveVo dailySaveVo) {
        try {
            JgDailyCheck dailyCheck = dailyInspectService.finaSaveInfo(dailySaveVo, false);
            return ResultEntity.success(dailyCheck);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存/临时保存检查项结果内容失败");
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 上传结果记录的文件
     *
     * @param checkId 日常检查结果表id
     * @param imgFile 二进制文件流
     * @param type    1-要点表；2-记录表
     * @return
     */
    @PostMapping("uploadResultRecord")
    public ResultEntity uploadResultRecord(Long checkId, @RequestPart(required = true, name = "imgFile") MultipartFile imgFile, String type
    ) {
        try {
            if (imgFile != null && StringUtils.isBlank(imgFile.getOriginalFilename())) {
                return ResultEntity.error("请上传文件");
            }
            String fileUrl = dailyInspectService.uploadResultRecord(checkId, imgFile, type);
            return ResultEntity.success(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传结果记录的文件失败");
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 查询检查完成的订单
     *
     * @param checkId 日常检查表id
     * @return
     */
    @GetMapping("getCheckResultInfo")
    public ResultEntity getCheckResultInfo(Long checkId) {
        try {
            Map<String, Object> result = dailyInspectService.getCheckResultInfo(checkId);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查完成的订单失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 查询检查内容的列表
     *
     * @param checkId 日常检查表JG_DAILY_CHECK  id
     * @return
     */
    @GetMapping("getCheckInfo")
    public ResultEntity getCheckInfo(Long checkId) {
        try {
            JgDailyCheck checkInfo = dailyInspectService.getCheckInfo(checkId);
            return ResultEntity.success(checkInfo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查信息失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 查询结果表需要的数据
     *
     * @param checkId 日常检查表JG_DAILY_CHECK  id
     * @return
     */
    @GetMapping("getResultTable")
    public ResultEntity getResultTable(Long checkId) {
        try {
            Map<String, Object> resultTable = dailyInspectService.getResultTable(checkId);
            return ResultEntity.success(resultTable);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查信息失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 查询检查内容的列表
     *
     * @param dailyStandardId 日常检查表id
     * @return
     */
    @GetMapping("getCheckContentList")
    public ResultEntity getCheckContentList(Long dailyStandardId) {
        try {
            List<Map<String, Object>> contentList = dailyInspectService.getCheckContentList(dailyStandardId);
            return ResultEntity.success(contentList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查内容的列表失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 保存告知单
     *
     * @param checkAddress         检查地址
     * @param checkPerson1Id       第一检查人id
     * @param checkPerson1SignFile 第一检查人签名文件流
     * @param checkPerson2Id       第二检查人id
     * @param checkPerson2SignFile 第二检查人签名文件流
     * @param checkId              检查ID
     * @param companySignFile      企业签名文件流
     * @param informFile           电子告知单文件流
     * @param isAvoid              是否回避0-否；1-是
     * @param notifyMatters
     * @param taskIds              合并关联任务的id
     * @return
     */
    @PostMapping("saveCheckInform")
    public ResultEntity saveCheckInform(Long checkId, Long checkPerson1Id, Long checkPerson2Id,
                                        String checkAddress, String notifyMatters, String isAvoid, String companySignFile
            , String checkPerson1SignFile
            , String checkPerson2SignFile
            , String informFile, String taskIds
    ) {
        try {
            String urlPath = dailyInspectService.saveCheckInform(checkId, checkPerson1Id, checkPerson2Id,
                    checkAddress, notifyMatters, isAvoid, companySignFile, checkPerson1SignFile, checkPerson2SignFile, informFile, taskIds);
            return ResultEntity.success(urlPath);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查内容的列表失败");
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 获取待办的专项检查任务
     *
     * @return
     */
    @GetMapping("getSpecialInspectList")
    public ResultEntity getSpecialInspectList(Long companyId) {
        try {
            List<Map<String, Object>> taskList = dailyInspectService.getSpecialInspectList(companyId);
            return ResultEntity.success(taskList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查内容的列表失败");
            return ResultEntity.error("操作失败");
        }
    }

}
